package Dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import Dao.UserDao;
import pojo.User;
import util.jdbc;

public class UserDaoImpl implements UserDao {

	@Override
	public int addUser(User u) {
		int rs=0;
		String sql="insert into users (id,name,password,sex,age)"
				+ "values(tj_seq01.nextval,?,?,?,?)";
		Connection con=null;
		PreparedStatement pst=null;
		con=jdbc.getConn();
		try {
			pst=con.prepareStatement(sql);
			pst.setString(1, u.getName());
			pst.setString(2, u.getPassword());
			pst.setBoolean(3, u.isSex());
			pst.setInt(4, u.getAge());
			rs=pst.executeUpdate();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
finally {
	jdbc.close(con, pst, null);
}
		return rs;
	}

	@Override
	public User findUser(String name, String password) {
		User user=null;
		ResultSet rs=null;
		PreparedStatement pStatement=null;
		String sql="select * from users where name=? and password=?";
		Connection cnConnection= jdbc.getConn();
		try {
			pStatement=cnConnection.prepareStatement(sql);
			pStatement.setString(1, name);
			pStatement.setString(2, password);
			rs=pStatement.executeQuery();
			if(rs.next()){
				user=new User();
				user.setId(rs.getInt("id"));
				user.setAge(rs.getInt("age"));
				user.setName(rs.getString("name"));
				user.setPassword(rs.getString("password"));
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally{
			jdbc.close(cnConnection, pStatement, rs);
		}	
		return user;
	}

	@Override
	public List<User> findAllUsers() {
		List<User> users=new ArrayList<User>();
		String sql="select * from item";
		Connection con=null;
		PreparedStatement pst=null;
		ResultSet rs=null;
		try {
			con=jdbc.getConn();
			pst=con.prepareStatement(sql);
			rs=pst.executeQuery();
			while(rs.next()){
				User u=new User();
				u.setId(rs.getInt("id"));
				u.setAge(rs.getInt("age"));
				u.setName(rs.getString("name"));
				u.setPassword(rs.getString("password"));
				users.add(u);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally {
			jdbc.close(con, pst, rs);
		}
		return users;
	}

	@Override
	public int fireUser(int id) {
		int rs=0;
		String sql="delete from users where id=?";
		Connection con=null;
		PreparedStatement pst=null;
		con=jdbc.getConn();
		try {
			pst=con.prepareStatement(sql);
			pst.setInt(1, id);
			rs=pst.executeUpdate();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally {
			jdbc.close(con, pst, null);
		}
		
		return rs;
	}

}
